package com.ytd.smartcanteen.weighting.util;

import com.ytd.common.dialog.ResultDialog;
import com.ytd.common.util.LogUtil;
import com.ytd.common.util.ThreadUtil;
import com.ytd.common.util.YtdConfig;
import com.ytd.smartcanteen.weighting.MainActivity;
import com.ytd.smartcanteen.weighting.bean.response.GetConsumeResponse;
import com.ytd.smartcanteen.weighting.devices.LEDManager;
import com.ytd.smartcanteen.weighting.devices.ScaleManager;
import com.ytd.smartcanteen.weighting.fragment.ConsumeFragment;

import java.math.BigDecimal;
import java.math.RoundingMode;

import cn.ytd.smartcanteen.weighting.R;

/**
 * 报警管理类
 *
 * @author gaoguanchao
 * @since 2023/12/5 0005
 */
public class ConsumeWarnUtil {
    /**
     * 水蒸气蒸发判断阈值
     */
    public static final double EVAPORATION_VALUE = 0.03;
    private static BigDecimal sAlarmThreshold = BigDecimal.valueOf(0.05);
    private static GetConsumeResponse sConsumeResponse;
    private static BigDecimal sLimitWeightOfTake;
    private static BigDecimal sTotalWeightOfTake;
    private static BigDecimal sStableWeight;
    private static BigDecimal sTempWeight;
    public static BigDecimal sAlarmWeight;
    private static boolean isWhetherLimitWeightOfTake = false;
    public static boolean isErrorEvent = false;
    private static boolean isLocal = false;

    public static void hide() {
        sConsumeResponse = null;
        isWhetherLimitWeightOfTake = false;
        sAlarmThreshold =
                BigDecimal.valueOf(YtdConfig.getAlarmThreshold()).divide(ConsumeFragment.multiplyValue, 3, RoundingMode.HALF_UP);

        sLimitWeightOfTake = null;
        sTotalWeightOfTake = null;
        isErrorEvent = false;
        isLocal = false;
        sTempWeight = ScaleManager.getInstance().getStableWeight();
    }

    public static void show(GetConsumeResponse getConsumeResponse, boolean local, BigDecimal stableWeight) {
        sConsumeResponse = getConsumeResponse;
        isWhetherLimitWeightOfTake = getConsumeResponse.whetherLimitWeightOfTake == 1;
        sLimitWeightOfTake = BigDecimal.valueOf(getConsumeResponse.limitWeightOfTake);
        sTotalWeightOfTake = BigDecimal.valueOf(getConsumeResponse.totalWeightOfTake);
        sStableWeight = stableWeight;
        isLocal = local;
    }

    public static void checkSneak(BigDecimal decimal) {
        if (sTempWeight == null) {
            sTempWeight = ScaleManager.getInstance().getStableWeight();
        }
        if (sTempWeight.compareTo(decimal.add(sAlarmThreshold)) > 0) {
            LogUtil.e("触发预警 丢失重量: " + sTempWeight.subtract(decimal).doubleValue() + "--浮动重量阈值: " +
                    sAlarmThreshold.doubleValue());
            isErrorEvent = true;
        }
    }

    public static void resultSneak(BigDecimal decimal, MainActivity mActivity) {
        if (sAlarmWeight != null || mActivity.isSetting()) {
            LogUtil.d("resultSneak isSetting");
            return;
        }
        if (sTempWeight == null) {
            sTempWeight = ScaleManager.getInstance().getStableWeight();
        }
        if (isErrorEvent && sTempWeight.compareTo(decimal.add(sAlarmThreshold)) > 0) {
            LogUtil.e("触发警报: 临时重量:" + sTempWeight.doubleValue() +
                    "--现重量: " + decimal.doubleValue() + "  丢失重量：" + sTempWeight.subtract(decimal).doubleValue());
            sAlarmWeight = sTempWeight;
            mActivity.showErrorDialog("请将托盘放入指定位置", R.mipmap.icon_location);
        } else {
            if (sTempWeight.compareTo(decimal) < 0) {
                sTempWeight = decimal;
                LogUtil.e("非消费状态重量变大，更新sTempWeight：" + sTempWeight.doubleValue());
            } else {
                BigDecimal subtract = sTempWeight.subtract(decimal);
                if (subtract.doubleValue() < EVAPORATION_VALUE) {//餐品蒸发会导致克数缓慢下降，在2-6分钟后，会触发累计丢失预警
                    sTempWeight = decimal;
                    LogUtil.e("非消费状态重量变小，更新sTempWeight：" + sTempWeight.doubleValue());
                }
            }
        }
    }

    private static boolean checkOverweight(BigDecimal decimal, MainActivity mActivity) {
        if (sStableWeight == null) {
            sStableWeight = ScaleManager.getInstance().getStableWeight();
            LogUtil.e("checkOverweight: mStableWeight == null" + sStableWeight.doubleValue());
        }
        if (sStableWeight.add(sAlarmThreshold).subtract(decimal).compareTo(BigDecimal.ZERO) < 0) {
            LogUtil.e("请勿压秤:" + sStableWeight.doubleValue() + "--现重量: " + decimal.doubleValue());
            mActivity.showOverweightDialog();
            return true;
        } else {
            ResultDialog resultDialog = mActivity.getResultDialog();
            if (resultDialog != null && resultDialog.isShowing() && mActivity.
                    getString(R.string.text_do_not_weigh_the_scale).equals(resultDialog.getText())) {
                LogUtil.e("请勿压秤:  hideWarnDialog");
                mActivity.hideWarnDialog();
            }
        }
        return false;
    }


    /**
     * 检测是否超量
     */
    private static void checkWhetherLimitWeightOfTake(BigDecimal decimal, MainActivity mActivity) {
        if (!isWhetherLimitWeightOfTake || sTotalWeightOfTake == null || sLimitWeightOfTake == null) {
            return;
        }
        if (sLimitWeightOfTake.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        BigDecimal value = sStableWeight.subtract(decimal).multiply(ConsumeFragment.multiplyValue);
        if (value.compareTo(BigDecimal.ZERO) < 0) {
            value = BigDecimal.ZERO;
        }
        BigDecimal subtract = sTotalWeightOfTake.add(value).subtract(sLimitWeightOfTake);
        int abs = subtract.intValue();
        if (abs != 0 && subtract.compareTo(BigDecimal.ZERO) > 0) {
            LogUtil.e("已超量:" + abs);
            mActivity.showLimitDialog(abs);
        } else {
            ResultDialog resultDialog = mActivity.getResultDialog();
            if (resultDialog != null && resultDialog.isShowing() &&
                    resultDialog.getText().contains(mActivity.getString(R.string.text_exceeded_split))) {
                LogUtil.e("已超量:  hideWarnDialog");
                mActivity.hideWarnDialog();
            }
        }
    }

    private static boolean checkBalance(BigDecimal changePrice, MainActivity mActivity) {
        if (YtdConfig.ConsumeModeOrder.equals(YtdConfig.getConsumeMode())) {
            //当为后支付模式时，不校验余额
            return false;
        }
        if (WeightConfig.getAmountCheck()) {
            ResultDialog resultDialog = mActivity.getResultDialog();
            if (sConsumeResponse.balance < (sConsumeResponse.totalConsume + changePrice.doubleValue())) {
                if (resultDialog == null || !resultDialog.isShowing() ||
                        !mActivity.getString(R.string.text_insufficient_balance).equals(resultDialog.getText())) {
                    LogUtil.e(
                            "余额不足 ： 余额: " + sConsumeResponse.balance + "   消费金额: " +
                                    changePrice.doubleValue());
                    mActivity.showResDialog(mActivity.getString(R.string.text_insufficient_balance), R.mipmap.icon_warn,
                            0,
                            false);
                    LEDManager.getInstance().showRed();
                    LogUtil.d("LEDManager showRed 余额不足");
                }
                return true;
            } else {
                if (resultDialog != null && resultDialog.isShowing() &&
                        "余额不足".equals(resultDialog.getText())) {
                    LogUtil.e("余额不足:  hideWarnDialog");
                    mActivity.hideWarnDialog();
                }
                return false;
            }
        }
        return false;
    }

    private static boolean checkLimitOnce(BigDecimal changePrice, MainActivity mActivity) {
        if (YtdConfig.getConsumeLimitOnceEnabled() && YtdConfig.getConsumeLimitOnceAmount() != 0) {
            String limitText = mActivity.getString(R.string.text_exceeding_limit);
            ResultDialog resultDialog = mActivity.getResultDialog();
            if (changePrice.subtract(BigDecimal.valueOf(YtdConfig.getConsumeLimitOnceAmount()))
                    .compareTo(BigDecimal.ZERO) > 0) {
                if (resultDialog == null || !resultDialog.isShowing() ||
                        !limitText.equals(resultDialog.getText())) {
                    LogUtil.e("单次消费限额 ： " + YtdConfig.getConsumeLimitOnceAmount() + "   消费金额: " +
                            changePrice.doubleValue());
                    ThreadUtil.executeMainDelayed(() -> {
                        mActivity.showResDialog(limitText, R.mipmap.icon_warn, 0, false);
                        LEDManager.getInstance().showRed();
                        LogUtil.d("LEDManager showRed 单次消费限额");
                    }, 100);
                }
                return true;
            } else {
                if (resultDialog != null && resultDialog.isShowing() &&
                        limitText.equals(resultDialog.getText())) {
                    mActivity.hideWarnDialog();
                }
            }
        }
        return false;
    }

    public static void checkWarn(MainActivity activity, BigDecimal decimal, BigDecimal changePrice) {
        if (checkOverweight(decimal, activity)) {
            return;
        }
        if (!isLocal && checkBalance(changePrice, activity)) {
            return;
        }
        if (!isLocal && checkLimitOnce(changePrice, activity)) {
            return;
        }
        checkWhetherLimitWeightOfTake(changePrice, activity);
    }

    public static void resetData() {
        sAlarmWeight = null;
        isErrorEvent = false;
        sTempWeight = null;
    }
}
